<template>
  <div>
    <el-card class="card">
      <el-page-header @back="goBack" content="确认订单信息"></el-page-header>
      <div style="margin-top:20px;">
        <span>选择地址：</span>
        <el-select v-model="value" placeholder="请选择地址" clearable>
          <el-option
            v-for="(value, index) in shippingData.list"
            :key="value.id"
            :label="value.id"
            :value="index"
          ></el-option>
        </el-select>
        <el-button
          type="text"
          @click="addShippingDialogVisible = true"
          style="margin-left:20px"
        >添加地址</el-button>
        <el-button type="text" @click="editShipping" v-if="value !== ''">编辑地址</el-button>
        <el-button type="text" @click="deleteShipping" v-if="value !== ''">删除地址</el-button>
      </div>
      <div v-if="value !== ''">
        {{shippingData.list[value].receiverName}}&nbsp;&nbsp;
        {{shippingData.list[value].receiverProvince}}
        {{shippingData.list[value].receiverCity}}
        {{shippingData.list[value].receiverDistrict}}
        {{shippingData.list[value].receiverAddress}}
        ...
      </div>
      <el-table :data="orderData.orderItemVoList" show-summary>
        <el-table-column width="50px">
          <template slot-scope="scope">
            <img
              src="@/assets/logo.png"
              v-real-img="realImg(orderData.imgHost,scope.row.productImage)"
              width="100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="currentUnitPrice" label="单价"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="totalPrice" label="总价"></el-table-column>
      </el-table>
      <el-button class="submitBtn" type="primary" @click="submitBtn">生成订单</el-button>
    </el-card>
    <el-dialog title="新增地址" :visible.sync="addShippingDialogVisible" width="800px" center>
      <el-form
        :rules="addShipFormRules"
        :model="addShippingForm"
        ref="addShipFormRef"
        label-width="100px"
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addShippingForm.name"></el-input>
        </el-form-item>
        <el-form-item label="省市区" required>
          <v-distpicker @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea"></v-distpicker>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addShippingForm.address"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="addShippingForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮政编码" prop="zip">
          <el-input v-model="addShippingForm.zip"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addShippingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddShipping">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="使用沙箱支付宝扫码支付"
      :visible.sync="payDialogVisible"
      width="50%"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      @closed="payDialogClosed"
    >
      <div class="qrDiv">
        <p>订单号：{{payOrderNo}}</p>
        <img src="@/assets/logo.png" v-real-img="realImg2(qrURL)" width="50%" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="cancelOrder">取消订单</el-button>
        <el-button @click="payDialogVisible = false">暂不支付</el-button>
        <el-button type="primary" @click="paysuccess">确认支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  inject: ['reload'],
  data() {
    return {
      queryInfo: {
        orderID: null,
        pageNum: 1,
        pageSize: 10
      },
      value: '',
      orderData: {},
      shippingData: [],
      addShippingDialogVisible: false,
      addShippingForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        address: '',
        zip: ''
      },
      addShipFormRules: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (value === null || value === '' || value.trim() === '') callback(new Error('收货人名字不能放空'))
              this.addShippingForm.name = value.trim()
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        address: [
          {
            validator: (rule, value, callback) => {
              if (value === null || value === '' || value.trim() === '') callback(new Error('请填写详细地址'))
              this.addShippingForm.address = value.trim()
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value === '') callback(new Error('必填项'))
              const v = /^1[3456789]\d{9}$/
              if (!v.test(value)) callback(new Error('请输入有效的手机号码'))
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        zip: [
          {
            validator: (rule, value, callback) => {
              if (value === '') callback(new Error('必填项'))
              const v = /^[0-9]\d{5}$/
              if (!v.test(value)) callback(new Error('请输入有效的邮政编码'))
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ]
      },
      //
      payDialogVisible: false,
      payOrderNo: '',
      qrURL: ''
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const { data: res } = await this.$axios.get('manage/order/get_order_cart_product')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.orderData = res.data
      this.getShipping()
    },
    async getShipping() {
      const { data: res } = await this.$axios.get('manage/shipping/list')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.shippingData = res.data
      console.log(this.shippingData)
    },
    goBack() {
      this.$router.push('/myCart')
    },
    realImg(host, img) {
      if (img === null || img === '') {
        return 'false'
      }
      return host + img
    },
    realImg2(imgURL) {
      if (imgURL === null || imgURL === '') {
        return 'false'
      }
      return imgURL
    },
    async submitBtn() {
      if (this.value === null || this.value === '') return this.$message.error('请选择地址')
      const info = new FormData()
      info.append('shippingID', this.shippingData.list[this.value].id)
      const { data: res } = await this.$axios.post('manage/order/create_order', info)
      if (res.status !== 0) return this.$message.error(res.msg)
      // todo : 等待支付功能开发完毕，进行对接
      // this.$router.push({
      //   name: 'pay',
      //   params: {
      //     orderNo: res.data.orderNo
      //   }
      // })
      this.payOrderNo = res.data.orderNo
      this.pay()
      // delete1588067409553
      // this.$confirm('订单提交成功\n订单号为：' + res.data.orderNo + '\n支付功能尚在开发...敬请期待！', '支付尚在开发', {
      //   confirmButtonText: '奥利给',
      //   cancelButtonText: '哦吼',
      //   type: 'success'
      // })
      //   .then(() => {
      //     this.$router.go(0)
      //   })
      //   .catch(() => {
      //     this.$router.go(0)
      //   })
    },
    onChangeProvince(a) {
      this.addShippingForm.province = a.value
    },
    onChangeCity(a) {
      this.addShippingForm.city = a.value
    },
    onChangeArea(a) {
      this.addShippingForm.district = a.value
    },
    submitAddShipping() {
      this.$refs.addShipFormRef.validate(async valid => {
        if (!valid) return
        if (this.addShippingForm.province === '' || this.addShippingForm.province === '省') {
          return this.$message.error('省市区必填项')
        } else if (this.addShippingForm.city === '' || this.addShippingForm.city === '市') {
          return this.$message.error('省市区必填项')
        } else if (this.addShippingForm.district === '' || this.addShippingForm.district === '区') {
          return this.$message.error('省市区必填项')
        }
        const { data: res } = await this.$axios.post('manage/shipping/add', {
          receiverName: this.addShippingForm.name,
          receiverProvince: this.addShippingForm.province,
          receiverCity: this.addShippingForm.city,
          receiverDistrict: this.addShippingForm.district,
          receiverAddress: this.addShippingForm.address,
          receiverPhone: this.addShippingForm.phone,
          receiverZip: this.addShippingForm.zip
        })
        if (res.status !== 0) return this.$message.error(res.msg)
        this.$message.success(res.msg)
        this.getShipping()
        this.$refs.addShipFormRef.resetFields()
        this.addShippingDialogVisible = false
      })
    },
    editShipping() {
      this.$message.info('编辑地址待优化')
    },
    deleteShipping() {
      this.$confirm('此操作将永久删除当前选中的地址，是否继续？', '删除提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete('manage/shipping/delete/' + this.shippingData.list[this.value].id)
          if (res.status !== 0) return this.$message.error(res.msg)
          this.getShipping()
          this.value = ''
          this.$message.success(res.data)
        })
        .catch(() => {})
    },
    // 支付界面
    async pay() {
      // 根据订单号，获取支付二维码
      console.log('获取支付二维码')
      const info = new FormData()
      info.append('orderNo', this.payOrderNo)
      const { data: res } = await this.$axios.post('manage/order/pay', info)
      console.log(res)
      // this.qrURL = 'http://192.168.111.1:80/qr-1588067409553.png'
      this.qrURL = res.data.qrUrl
      this.payDialogVisible = true
    },
    //
    async paysuccess() {
      console.log('检查是否已支付')
      const info = new FormData()
      info.append('orderNo', this.payOrderNo)
      const { data: res } = await this.$axios.post('manage/order/query_order_pay_status', info)
      console.log(res)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.$message.success(res.msg)
      // 支付成功的操作
      this.payDialogVisible = false
    },
    //
    payDialogClosed() {
      this.qrURL = ''
      this.payOrderNo = ''
      console.log('关闭支付框')
      this.$router.push('/myOrder')
    },
    // 取消订单
    async cancelOrder() {
      console.log('取消订单')
      const { data: res } = await this.$axios.delete('manage/order/cancel_order/' + this.payOrderNo)
      console.log(res)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.$message.success(res.msg)
      this.$router.push('/myOrder')
    }
  }
}
</script>

<style lang="less" scoped>
.card {
  margin-top: 50px;
}
.submitBtn {
  margin-top: 20px;
  margin-left: 48%;
}
.qrDiv {
  text-align: center;
}
</style>
